package me.firstapp.service.weixin.soft.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.common.utils.MD5Utils;
import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.weixin.jinbi.JinBiAccount;
import me.firstapp.module.weixin.jinbi.JinBiAccountTrace;
import me.firstapp.module.weixin.member.Member;
import me.firstapp.module.weixin.member.PaymentRecord;
import me.firstapp.module.weixin.member.SoftFee;
import me.firstapp.module.weixin.order.MobileFareOrder;
import me.firstapp.module.weixin.order.SoftOrder;
import me.firstapp.module.weixin.system.ThisSystem;
import me.firstapp.module.weixin.weibi.WeiBiAccount;
import me.firstapp.module.weixin.weibi.WeiBiAccountTrace;
import me.firstapp.module.weixin.weibi.WeiBiAccountTrace.ChangeType;
import me.firstapp.repository.weixin.jinbi.JinBiAccountRepository;
import me.firstapp.repository.weixin.jinbi.JinBiAccountTraceRepository;
import me.firstapp.repository.weixin.member.MemberRepository;
import me.firstapp.repository.weixin.member.PaymentRecordRepository;
import me.firstapp.repository.weixin.member.SoftFeeRepository;
import me.firstapp.repository.weixin.order.SoftOrderRepository;
import me.firstapp.repository.weixin.system.ThisSystemRepository;
import me.firstapp.repository.weixin.weibi.WeiBiAccountRepository;
import me.firstapp.repository.weixin.weibi.WeiBiAccountTraceRepository;
import me.firstapp.service.weixin.soft.SoftOrderService;

@Service
public class SoftOrderServiceImpl implements SoftOrderService {

	private static Logger logger = LoggerFactory.getLogger(SoftOrderServiceImpl.class);

	@Autowired
	private MemberRepository memberRepository;

	@Autowired
	private SoftFeeRepository softFeeRepository;

	@Autowired
	private SoftOrderRepository softOrderRepository;

	@Autowired
	private WeiBiAccountRepository weiBiAccountRepository;

	@Autowired
	private WeiBiAccountTraceRepository weiBiAccountTraceRepository;

	@Autowired
	private JinBiAccountRepository jinBiAccountRepository;

	@Autowired
	private JinBiAccountTraceRepository jinBiAccountTraceRepository;

	@Autowired
	private PaymentRecordRepository paymentRecordRepository;

	@Autowired
	private ThisSystemRepository thisSystemRepository;

	@Override
	public SoftOrder executeCreateSoftOrder(String openId, Integer vipLevel) {
		Member member = memberRepository.findMemberByOpenId(openId);
		if (null == member) {
			throw new ServiceException(StatusHouse.STATUS_MEMBER_NOT_EXIST);
		}
		String vipStr = "";
		if (member.getVipLevel() == 1) {
			vipStr = "会员服务";
		} else if (member.getVipLevel() == 2) {
			vipStr = "代理服务";
		}
		if (member.getVipLevel() > vipLevel) {
			throw new ServiceException("error", "你目前的服务是【" + vipStr + "】,无需购买该服务！");
		}
		SoftFee softFee = softFeeRepository.findSoftFeeByLevel(vipLevel);
		if (null == softFee) {
			throw new ServiceException(StatusHouse.STATUS_PRODUCT_NOT_EXIST);
		}
		ThisSystem thisSystem = thisSystemRepository.findThisSystem();
		member.setFlow(member.getFlow() + 1);
		memberRepository.update(member);

		SoftOrder softOrder = new SoftOrder();
		String orderNoStart = SoftOrder.ORDER_NO_START + DateUtils.getNowStr("yyMMdd") + member.getId();
		String orderNoEnd = String.valueOf(member.getFlow());
		int lenth = thisSystem.getOrderNoLength() - orderNoStart.length() - orderNoEnd.length();
		StringBuffer sb = new StringBuffer("");
		for (int i = 0; i < lenth; i++) {
			sb.append(String.valueOf(StrUtils.getRandomInt()));
		}
		softOrder.setOrderNo(orderNoStart + sb.toString() + orderNoEnd);
		softOrder.setOpenId(openId);
		softOrder.setCardNo(member.getCardNo());
		softOrder.setChiefOpenId(member.getChiefOpenId());
		softOrder.setChiefCardNo(member.getChiefCardNo());
		softOrder.setVipLevel(vipLevel);
		softOrder.setAmount(softFee.getPrice());
		softOrder.setPayAmount(softFee.getPrice());
		softOrder.setGivePoint(softFee.getPrice());
		softOrder.setChiefBaseVipJinBi(softFee.getChiefBaseVipJinBi());
		softOrder.setChiefHighVipJinBi(softFee.getChiefHighVipJinBi());
		softOrder.setChiefBaseVipPoint(softFee.getChiefBaseVipPoint());
		softOrder.setChiefHighVipPoint(softFee.getChiefHighVipPoint());
		softOrder.setChiefJinBi(BigDecimal.ZERO);
		softOrder.setChiefPoint(BigDecimal.ZERO);
		softOrder.setChiefChiefJinBi(BigDecimal.ZERO);
		softOrder.setStatus(SoftOrder.STATUS_NOT_PAY);
		softOrder.setCreateTime(new Date());
		softOrder.setSettleFlag(SoftOrder.SETTLE_FLAG_NOT);
		softOrderRepository.save(softOrder);
		return softOrder;
	}

	@Override
	public List<SoftOrder> findOrders(Integer status) {
		return softOrderRepository.findOrders(status);
	}

	@Override
	public SoftOrder executeUpdate(SoftOrder softOrder) {
		softOrderRepository.update(softOrder);
		return softOrder;
	}

	@Override
	public List<SoftOrder> findOrders(Integer status, Integer settleFlag) {
		return softOrderRepository.findOrders(status, settleFlag);
	}

	@Override
	public SoftOrder executeSettle(SoftOrder softOrder) {
		if (SoftOrder.SETTLE_FLAG_YES == softOrder.getSettleFlag()) {
			return softOrder;
		}
		if (SoftOrder.STATUS_COMPLETE != softOrder.getStatus()) {
			return softOrder;
		}
		Member member = memberRepository.findMemberByOpenId(softOrder.getOpenId());

		// ==================模块二：上级结算 start=======================
		Member chiefMember = memberRepository.findMemberByOpenId(softOrder.getChiefOpenId());
		if (null == chiefMember) {
			softOrder.setChiefJinBi(BigDecimal.ZERO);
			softOrder.setChiefPoint(BigDecimal.ZERO);
			softOrder.setChiefChiefJinBi(BigDecimal.ZERO);
			// 更新订单结算标志
			softOrder.setSettleFlag(MobileFareOrder.SETTLE_FLAG_YES);
			softOrder.setSettleTime(new Date());
			softOrderRepository.update(softOrder);
			logger.info("软件订单【" + softOrder.getOrderNo() + "】已结算完成。");
			return softOrder;
		}
		if (chiefMember.getVipLevel() == Member.VIP_LEVEL_FANS) {
			softOrder.setChiefJinBi(BigDecimal.ZERO);
			softOrder.setChiefPoint(BigDecimal.ZERO);
			logger.info("用户【" + member.getCardNo() + "】的上级【" + chiefMember.getCardNo() + "】的等级为粉丝，无需结算");
		} else if (Member.STATUS_NO_USE == chiefMember.getStatus()
				|| Member.FOLLOW_STATUS_NO == chiefMember.getFollowStatus()) {
			softOrder.setChiefJinBi(BigDecimal.ZERO);
			softOrder.setChiefPoint(BigDecimal.ZERO);
			logger.info("用户【" + member.getCardNo() + "】的上级【" + chiefMember.getCardNo() + "】的被禁用或取消关注，无需结算");
		} else {
			// ==========上级积分结算 start=============
			WeiBiAccount chiefWeiBiAccount = weiBiAccountRepository
					.findWeiBiAccountByCardNoAndOpenId(chiefMember.getCardNo(), chiefMember.getOpenId());
			if (!MD5Utils.verify(chiefWeiBiAccount.getBalance().doubleValue() * 10000 + "",
					chiefWeiBiAccount.getEncryption())) {
				softOrder.setChiefPoint(BigDecimal.ZERO);
				logger.info("用户【" + member.getCardNo() + "】的上级【" + chiefMember.getCardNo() + "】的积分账户金额异常!");
			} else {
				BigDecimal chiefMemberWeiBiChangeValue = BigDecimal.ZERO;
				if (chiefMember.getVipLevel() == Member.VIP_LEVEL_BASE) {
					chiefMemberWeiBiChangeValue = softOrder.getChiefBaseVipPoint();
				} else if (chiefMember.getVipLevel() == Member.VIP_LEVEL_HIGHT) {
					chiefMemberWeiBiChangeValue = softOrder.getChiefHighVipPoint();
				}
				if (chiefMemberWeiBiChangeValue.doubleValue() <= 0.00009999) {
					softOrder.setChiefPoint(BigDecimal.ZERO);
					logger.info("订单【" + softOrder.getOrderNo() + "】待赠送购买者上级的积分为0!");
				} else {
					WeiBiAccountTrace chiefMemberWeiBiAccountTrace = new WeiBiAccountTrace();
					chiefMemberWeiBiAccountTrace.setWeiBiAccountId(chiefWeiBiAccount.getId());
					chiefMemberWeiBiAccountTrace.setChangeType(ChangeType.FANS_CONSUME_ADD);
					chiefMemberWeiBiAccountTrace.setBeforeValue(chiefWeiBiAccount.getBalance());
					chiefMemberWeiBiAccountTrace.setChangeValue(chiefMemberWeiBiChangeValue);
					BigDecimal chiefMemberWeiBiAfterValue = chiefWeiBiAccount.getBalance()
							.add(chiefMemberWeiBiChangeValue).setScale(4, RoundingMode.HALF_UP);
					chiefMemberWeiBiAccountTrace.setAfterValue(chiefMemberWeiBiAfterValue);
					chiefMemberWeiBiAccountTrace.setChangeTime(new Date());
					chiefMemberWeiBiAccountTrace
							.setChangeDate(Integer.valueOf(DateUtils.getDateStr(new Date(), "yyyyMMdd")));
					weiBiAccountTraceRepository.save(chiefMemberWeiBiAccountTrace);

					chiefWeiBiAccount.setBalance(chiefMemberWeiBiAfterValue);
					chiefWeiBiAccount
							.setEncryption(MD5Utils.generate(chiefMemberWeiBiAfterValue.doubleValue() * 10000 + ""));
					chiefWeiBiAccount.setUpdateTime(new Date());
					weiBiAccountRepository.update(chiefWeiBiAccount);
					softOrder.setChiefPoint(chiefMemberWeiBiChangeValue);
				}

			}
			// ==========上级积分结算 end=============

			// ==========上级贝币结算 start=============
			JinBiAccount chiefMemberJinBiAccount = jinBiAccountRepository
					.findJinBiAccountByCardNoAndOpenId(chiefMember.getCardNo(), chiefMember.getOpenId());
			if (!MD5Utils.verify(chiefMemberJinBiAccount.getBalance().doubleValue() * 10000 + "",
					chiefMemberJinBiAccount.getEncryption())) {
				softOrder.setChiefJinBi(BigDecimal.ZERO);
				logger.info("用户【" + member.getCardNo() + "】的上级【" + chiefMember.getCardNo() + "】的贝币账户金额异常!");
			} else {
				BigDecimal chiefMemberJinBiChangeValue = BigDecimal.ZERO;
				if (chiefMember.getVipLevel() == Member.VIP_LEVEL_BASE) {
					chiefMemberJinBiChangeValue = softOrder.getChiefBaseVipJinBi();
				} else if (chiefMember.getVipLevel() == Member.VIP_LEVEL_HIGHT) {
					chiefMemberJinBiChangeValue = softOrder.getChiefHighVipJinBi();
				}
				if (chiefMemberJinBiChangeValue.doubleValue() <= 0.00009999) {
					softOrder.setChiefJinBi(BigDecimal.ZERO);
					logger.info("订单【" + softOrder.getOrderNo() + "】待赠送购买者上级的贝币为0!");
				} else {
					JinBiAccountTrace chiefMemberinBiAccountTrace = new JinBiAccountTrace();
					chiefMemberinBiAccountTrace.setJinBiAccountId(chiefMemberJinBiAccount.getId());
					chiefMemberinBiAccountTrace.setChangeType(
							me.firstapp.module.weixin.jinbi.JinBiAccountTrace.ChangeType.FANS_CONSUME_ADD);
					chiefMemberinBiAccountTrace.setBeforeValue(chiefMemberJinBiAccount.getBalance());
					chiefMemberinBiAccountTrace.setChangeValue(chiefMemberJinBiChangeValue);
					BigDecimal chiefMemberJinBiAfterValue = chiefMemberJinBiAccount.getBalance()
							.add(chiefMemberJinBiChangeValue).setScale(4, RoundingMode.HALF_UP);
					chiefMemberinBiAccountTrace.setAfterValue(chiefMemberJinBiAfterValue);
					chiefMemberinBiAccountTrace.setChangeTime(new Date());
					chiefMemberinBiAccountTrace
							.setChangeDate(Integer.valueOf(DateUtils.getDateStr(new Date(), "yyyyMMdd")));
					jinBiAccountTraceRepository.save(chiefMemberinBiAccountTrace);

					chiefMemberJinBiAccount.setBalance(chiefMemberJinBiAfterValue);
					chiefMemberJinBiAccount
							.setEncryption(MD5Utils.generate(chiefMemberJinBiAfterValue.doubleValue() * 10000 + ""));
					chiefMemberJinBiAccount.setUpdateTime(new Date());
					jinBiAccountRepository.update(chiefMemberJinBiAccount);
					softOrder.setChiefJinBi(chiefMemberJinBiChangeValue);
				}
			}
			// ==========上级贝币结算 end===============
		}
		// ==================上级结算 end=======================

		// ===========模块三：上级的上级如果是代理级别，则可吃下级代理的返利[返利计算：支付金额x2%x50%]==============
		Member chiefChiefMember = memberRepository.findMemberByOpenId(chiefMember.getChiefOpenId());
		if (null == chiefChiefMember) {
			softOrder.setChiefChiefJinBi(BigDecimal.ZERO);
			// 更新订单结算标志
			softOrder.setSettleFlag(MobileFareOrder.SETTLE_FLAG_YES);
			softOrder.setSettleTime(new Date());
			softOrderRepository.update(softOrder);
			logger.info("软件订单【" + softOrder.getOrderNo() + "】已结算完成。");
			return softOrder;
		}
		if (Member.STATUS_NO_USE == chiefChiefMember.getStatus()
				|| Member.FOLLOW_STATUS_NO == chiefChiefMember.getFollowStatus()
				|| Member.STATUS_NO_USE == chiefMember.getStatus()
				|| Member.FOLLOW_STATUS_NO == chiefMember.getFollowStatus()) {
			softOrder.setChiefChiefJinBi(BigDecimal.ZERO);
			logger.info("用户【" + member.getCardNo() + "】的上级【" + chiefMember.getCardNo() + "】的上级【"
					+ chiefChiefMember.getCardNo() + "】被禁用或取消关注，无需结算");
		} else if (Member.VIP_LEVEL_HIGHT == chiefMember.getVipLevel()
				&& Member.VIP_LEVEL_HIGHT == chiefChiefMember.getVipLevel()) {
			BigDecimal changeJinBiValue = softOrder.getPayAmount().multiply(new BigDecimal(0.002))
					.multiply(new BigDecimal(0.5)).setScale(4, RoundingMode.HALF_UP);
			if (changeJinBiValue.doubleValue() > 0.000099999) {
				JinBiAccount jinBiAccount = jinBiAccountRepository
						.findJinBiAccountByCardNoAndOpenId(chiefChiefMember.getCardNo(), chiefChiefMember.getOpenId());
				if (MD5Utils.verify(jinBiAccount.getBalance().doubleValue() * 10000 + "",
						jinBiAccount.getEncryption())) {
					JinBiAccountTrace jinBiAccountTrace = new JinBiAccountTrace();
					jinBiAccountTrace.setJinBiAccountId(jinBiAccount.getId());
					jinBiAccountTrace.setChangeType(
							me.firstapp.module.weixin.jinbi.JinBiAccountTrace.ChangeType.JINBI_ADD_DAILI);
					jinBiAccountTrace.setBeforeValue(jinBiAccount.getBalance());
					jinBiAccountTrace.setChangeValue(changeJinBiValue);
					BigDecimal afterValue = jinBiAccount.getBalance().add(changeJinBiValue).setScale(4,
							RoundingMode.HALF_UP);
					jinBiAccountTrace.setAfterValue(afterValue);
					jinBiAccountTrace.setChangeTime(new Date());
					jinBiAccountTrace.setChangeDate(Integer.valueOf(DateUtils.getDateStr(new Date(), "yyyyMMdd")));
					jinBiAccountTraceRepository.save(jinBiAccountTrace);

					jinBiAccount.setBalance(afterValue);
					jinBiAccount.setEncryption(MD5Utils.generate(afterValue.doubleValue() * 10000 + ""));
					jinBiAccount.setUpdateTime(new Date());
					jinBiAccountRepository.update(jinBiAccount);

					softOrder.setChiefChiefJinBi(changeJinBiValue);
				} else {
					softOrder.setChiefChiefJinBi(BigDecimal.ZERO);
					logger.info("用户【" + member.getCardNo() + "】的上级【" + chiefMember.getCardNo() + "】的上级【"
							+ chiefChiefMember.getCardNo() + "】的贝币账户金额异常!");
				}
			} else {
				softOrder.setChiefChiefJinBi(BigDecimal.ZERO);
			}
		}
		// 更新订单结算标志
		softOrder.setSettleFlag(MobileFareOrder.SETTLE_FLAG_YES);
		softOrder.setSettleTime(new Date());
		softOrderRepository.update(softOrder);
		logger.info("软件订单【" + softOrder.getOrderNo() + "】已结算完成。");
		return softOrder;
	}

	@Override
	public SoftOrder findByOrderNo(String orderNo) {
		return softOrderRepository.findByOrderNo(orderNo);
	}

	@Override
	public void executeConfirmOrder(SoftOrder softOrder) {
		if (null == softOrder) {
			return;
		}
		if (SoftOrder.STATUS_NOT_PAY != softOrder.getStatus()) {
			return;
		}
		softOrder.setStatus(SoftOrder.STATUS_PAYED);
		softOrder.setAccountDate(new Date());
		softOrderRepository.update(softOrder);
	}

	@Override
	public void executeSavePaymentRecord(SoftOrder softOrder, String thirdPayNo, Integer status, String errorCode,
			String errorDesc) {
		if (softOrder == null) {
			return;
		}
		if (SoftOrder.STATUS_PAYED != softOrder.getStatus()) {
			return;
		}
		PaymentRecord paymentRecord = new PaymentRecord();
		paymentRecord.setOrderNo(softOrder.getOrderNo());
		paymentRecord.setOpenId(softOrder.getOpenId());
		paymentRecord.setCardNo(softOrder.getCardNo());
		paymentRecord.setThirdPayNo(thirdPayNo);
		paymentRecord.setPayAmount(softOrder.getPayAmount());
		paymentRecord.setStatus(status);
		paymentRecord.setPayTime(new Date());
		paymentRecord.setErrorCode(errorCode);
		paymentRecord.setErrorDesc(errorDesc);
		paymentRecordRepository.save(paymentRecord);

	}

	@Override
	public SoftOrder executeCompleteOrder(SoftOrder softOrder) {
		if (SoftOrder.STATUS_PAYED != softOrder.getStatus()) {
			return softOrder;
		}
		Member member = memberRepository.findMemberByOpenId(softOrder.getOpenId());

		SoftFee softFee = softFeeRepository.findSoftFeeByLevel(softOrder.getVipLevel());
		if (softFee.getValidDays() == 0) {
			member.setExpireDate(DateUtils.getDateFromDateStr("2117-09-09 23:59:59", "yyyy-MM-dd HH:mm:ss"));
		} else {
			if (Member.VIP_LEVEL_FANS == member.getVipLevel()) {
				member.setExpireDate(DateUtils.getBeforeOrNextDay(new Date(), softFee.getValidDays() + 1));
			} else if (softOrder.getVipLevel() == member.getVipLevel()) {
				member.setExpireDate(DateUtils.getBeforeOrNextDay(member.getExpireDate(), softFee.getValidDays() + 1));
			} else {
				member.setExpireDate(DateUtils.getBeforeOrNextDay(new Date(), softFee.getValidDays() + 1));
			}
		}
		member.setVipLevel(softOrder.getVipLevel());
		memberRepository.update(member);
		softOrder.setStatus(SoftOrder.STATUS_COMPLETE);
		softOrder.setCompleteTime(new Date());
		softOrderRepository.update(softOrder);

		// ==========模块一：购物者积分结算 start=============
		WeiBiAccount memberWeiBiAccount = weiBiAccountRepository.findWeiBiAccountByCardNoAndOpenId(member.getCardNo(),
				member.getOpenId());
		if (!MD5Utils.verify(memberWeiBiAccount.getBalance().doubleValue() * 10000 + "",
				memberWeiBiAccount.getEncryption())) {
			logger.info("用户【" + member.getCardNo() + "】积分账户金额异常!");
		} else {
			if (softOrder.getGivePoint().doubleValue() <= 0.000099) {
				logger.info("订单【" + softOrder.getOrderNo() + "】待赠送购买者积分为0!");
			} else {
				WeiBiAccountTrace memberWeiBiAccountTrace = new WeiBiAccountTrace();
				memberWeiBiAccountTrace.setWeiBiAccountId(memberWeiBiAccount.getId());
				memberWeiBiAccountTrace.setChangeType(ChangeType.SELF_CONSUME_ADD);
				memberWeiBiAccountTrace.setBeforeValue(memberWeiBiAccount.getBalance());
				memberWeiBiAccountTrace.setChangeValue(softOrder.getGivePoint());
				BigDecimal memberWeiBiAfterValue = memberWeiBiAccount.getBalance().add(softOrder.getGivePoint())
						.setScale(4, RoundingMode.HALF_UP);
				memberWeiBiAccountTrace.setAfterValue(memberWeiBiAfterValue);
				memberWeiBiAccountTrace.setChangeTime(new Date());
				memberWeiBiAccountTrace.setChangeDate(Integer.valueOf(DateUtils.getDateStr(new Date(), "yyyyMMdd")));
				weiBiAccountTraceRepository.save(memberWeiBiAccountTrace);

				memberWeiBiAccount.setBalance(memberWeiBiAfterValue);
				memberWeiBiAccount.setEncryption(MD5Utils.generate(memberWeiBiAfterValue.doubleValue() * 10000 + ""));
				memberWeiBiAccount.setUpdateTime(new Date());
				weiBiAccountRepository.update(memberWeiBiAccount);
			}
		}
		// ==========购物者积分结算 end=============

		return softOrder;
	}

	@Override
	public Page<SoftOrder> findSoftOrderPage(Integer pageNo, Integer pageSize, Map<String, Object> searchParams,
			String sortParam, String sortType, Date startTime, Date endTime) {
		return softOrderRepository.findSoftOrderPage(pageNo, pageSize, searchParams, sortParam, sortType, startTime,
				endTime);
	}

}
